package com.egg.basic.config.email;

import cn.hutool.extra.mail.MailAccount;
import com.egg.basic.util.EmailUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * 邮箱配置
 */
@Profile({"prod", "test", "dev"})
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "email")
public class EmailConfig {


    // 是否需要用户名密码验证
    private Boolean auth;
    // 是否使用SSL安全连接
    private Boolean sslEnable;
    // 是否使用STARTTLS安全连接
    private Boolean startttlsEnable;
    // 用户名
    private String user;
    // SMTP服务器域名
    private String host;
    // SMTP服务端口
    private Integer port;
    // 密码
    private String pass;
    // 密码加密KEY
    private String passAesEncryptKey;
    // 发送方，遵循RFC-822标准
    private String from;


    @Bean
    public MailAccount initMailConfig() {
        try {
            MailAccount account = new MailAccount();
            // 设置用户
            account.setAuth(getAuth());
            // ssl方式发送
            account.setSslEnable(getSslEnable());
            // 使用STARTTLS安全连接
            account.setStarttlsEnable(getStartttlsEnable());
            account.setUser(getUser());
            account.setHost(getHost());
            account.setPort(getPort());
            //account.setPass(SecureUtil.aesDecrypt(getPassAesEncryptKey(), getPass()));
            account.setPass(getPass());
            account.setFrom(getFrom());
            log.info("初始化成功 {}", MailAccount.class.getName());
            return account;
        } catch (Exception e) {
            log.error("初始化失败 {} 原因 {}", MailAccount.class.getName(), e.getMessage());
        }
        return null;
    }

    /**
     * 装配
     *
     * @return
     */
    @Bean
    EmailUtil initEmailUtil(MailAccount mailAccount) {
        if (null == mailAccount) {
            log.error("初始化失败 {} 原因 {}", EmailUtil.class.getName(), MailAccount.class.getName() + "为null");
            return new EmailUtil();
        }
        EmailUtil emailUtil = new EmailUtil();
        emailUtil.setMailAccount(mailAccount);
        log.info("初始化成功 {}", EmailUtil.class.getName());
        return emailUtil;
    }


}